<?php
namespace  Common\Controller; 
use Common\Util\ConfigUtils; 
use Common\Util\EncryUtils; 
use Common\Controller\BaseController;
use Common\Util\UserUtils;
use Common\Model\WeixinMemberModel;
/**
 * 登录管理
 * @author liuyang
 * 
 */   

class LoginController extends BaseController 
{
	public  $weixinUser = null;  
	public  $userId = 0;
	 
	public function _initialize(){
		//$this->_validateurl(); 
		$this->_initlogin();
	}
	
	
	public function _initlogin(){ 
		$rst = array();
		 
		if(!$this->getUser()){
		    cookie(UserUtils::LOGIN_WEIXIN_OPENID_USER_COOKIE,null,time()-24*3600*3,"/");
			$rst['msg']="token失效";
			$rst['result']=-100; 
			$paramlist = $_REQUEST;   
			unset($paramlist['callbackurl']);
			$paramStr = $this->getUrlParam($paramlist); 
			$authUrl = ConfigUtils::getConfig('WEIXIN_AUTH_URL');
			if(strpos($authUrl, "?") !== false){
			    $authUrl .= "&".$paramStr;
			} else{
			    $authUrl .= "?".$paramStr;
			}
			$loginUrl = $authUrl;
			$curUrl = $this->getPostParam("login_url", ConfigUtils::getConfig('WEB_URL'));
			cookie(UserUtils::LAST_URL,$curUrl,time()+3600,"/");
			$rst['login_url']=$loginUrl;
			$this->formatjson($rst); 
		} 
	}
	
	public function getUser(){  
	    $test = $this->getPostParam("test");   
	    if($test==1){
            $openId = "otNbOt-FqUyOcBRvRSSTV_kHt9RU"; 
            cookie(UserUtils::LOGIN_WEIXIN_OPENID_USER_COOKIE,EncryUtils::encrypt($openId),time()+24*3600*3,"/");
            $unionId = "oEQIM0xIa2PweHWabWml4N-l15fw";
            cookie(UserUtils::LOGIN_WEIXIN_USER_COOKIE,EncryUtils::encrypt($unionId),time()+24*3600*3,"/");
	    }else if( $test==2){ 
            $openId = "1234567890"; 
            cookie(UserUtils::LOGIN_WEIXIN_OPENID_USER_COOKIE,EncryUtils::encrypt($openId),time()+24*3600*3,"/");
            $unionId = "1234567890";
            cookie(UserUtils::LOGIN_WEIXIN_USER_COOKIE,EncryUtils::encrypt($unionId),time()+24*3600*3,"/");
	    }  
	       $unionId = cookie(UserUtils::LOGIN_WEIXIN_USER_COOKIE);
	       if($unionId==null){
	           $unionId = $this->getPostParam("token", "");
	       }
	      
		if($unionId != null  && strlen($unionId)>8  ){ 
		      $unionId = EncryUtils::decrypt($unionId); 
		      $obj = (new WeixinMemberModel())->getByUnionId($unionId); 
		      if($obj['id']>0){ 
		          $this->weixinUser = $obj;
		          $this->userId = $obj['user_id'];
		          return true;
		      }else{
		          cookie(UserUtils::LOGIN_WEIXIN_USER_COOKIE,0,time()-24*3600*3,"/");
		          return false;
		      } 
		}else{
		    return false;
		}
	}
	
	public function getCurUserId(){
	    return $this->userId;
	}
	 
    
}


?>